package com.gameley.dmgtpf.common.core.aspect;

import com.gameley.dmgtpf.common.utils.PubEnvUtil;
import com.gameley.dmgtpf.common.utils.TokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 
 **
 * @qualiFild MyDoneTimeAspect.java<br>
 * @author：LiBencheng<br>
 * @date Created on 2021年7月29日<br>
 * @version 1.0<br>
 */
@Aspect
@Component
public class MyDoneTimeAspect
{
    @Around("@annotation(doneTime)")
    public Object around(ProceedingJoinPoint joinPoint, MyDoneTime doneTime) throws Throwable
    {
        long start = System.currentTimeMillis();
        System.err.println(doneTime.param() + "  方法开始运行时间是:" + new Date());
        String checkToken = "";
        Signature signature = joinPoint.getSignature();
        // 2.最关键的一步:通过这获取到方法的所有参数名称的字符串数组
        MethodSignature methodSignature = (MethodSignature) signature;
        // 1.这里获取到所有的参数值的数组
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];
        if (null == request)
        {
            return PubEnvUtil.getErrorMsg(" 接口没有定义 HttpServletRequest，和HttpServletResponse");
        }
        String token = request.getHeader("token");
        String methodName = methodSignature.getMethod().getName();
        if (!"userLogin".equals(methodName) && !"userLogout".equals(methodName))
        {
            checkToken = TokenUtil.checkToken(token);
            // 非法
            if (TokenUtil.TOKEN_ERROR.equals(checkToken))
            {
                System.err.println("方法结束时间是:" + new Date() + "---->一共运行{[" + (System.currentTimeMillis() - start) + "ms]}");
                return PubEnvUtil.getFailMsg("token illegal [" + token + "]");
            }
            // 过期
            if (TokenUtil.TOKEN_OVERDUE.equals(checkToken))
            {
                System.err.println("方法结束时间是:" + new Date() + "---->一共运行{[" + (System.currentTimeMillis() - start) + "ms]}");
                return PubEnvUtil.getFailMsg("token overdue [" + token + "]");
            }
        }
        if ("userLogout".equals(methodName))
        {
            TokenUtil.removeToken(token);
        }
        
        Object o = joinPoint.proceed();
        // 失效
        if (TokenUtil.TOKEN_FAILURE.equals(checkToken))
        {
                TokenUtil.removeToken(token);
        }
        
        System.err.println("方法结束时间是:" + new Date() + "---->一共运行{[" + (System.currentTimeMillis() - start) + "ms]}");
        return o;
    }
}
